package com.example.lianjuan.Presenter.impl.impl;

import com.example.lianjuan.Model.API;
import com.example.lianjuan.Model.domain.Categories;
import com.example.lianjuan.Presenter.impl.IHomePresenter;
import com.example.lianjuan.Utils.LogUtils;
import com.example.lianjuan.Utils.RetrofitManang;
import com.example.lianjuan.View.IHomeCallback;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class HomePresenterImpl implements IHomePresenter {

    private IHomeCallback mCallback;

    @Override
    public void getCategory() {
        mCallback.onLoadLoading();
        Retrofit mRetrofit = RetrofitManang.getRetrofitManang().getRetrofit();
        API api = mRetrofit.create(API.class);
        Call<Categories> categories = api.getCategories();
        categories.enqueue(new Callback<Categories>() {
            @Override
            public void onResponse(Call<Categories> call, Response<Categories> response) {
                int code = response.code();
                LogUtils.d(HomePresenterImpl.this, "------>" + code);
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    Categories body = response.body();
                    if (mCallback != null || body.getData().size() != 0) {
                        LogUtils.d(HomePresenterImpl.this, "------>" + body.toString());
                        mCallback.onCategoriseLoaded(body);
                        mCallback.onLoadNone();
                    } else {
                        mCallback.onLoadEmpty();
                    }
                } else {
                    if (mCallback != null) {
                        mCallback.onNetworkError();
                    }
                }
            }

            @Override
            public void onFailure(Call<Categories> call, Throwable t) {
                LogUtils.d(HomePresenterImpl.this, t.toString());
                mCallback.onNetworkError();
            }
        });
    }

    @Override
    public void registerViewCallback(IHomeCallback callback) {
        this.mCallback = callback;
    }

    @Override
    public void unregisterViewCallback(IHomeCallback callback) {
        mCallback = null;
    }
}
